(function () {
  const imgs = {
    small: ["imgA_1.jpg", "imgB_1.jpg", "imgC_1.jpg"],
    middle: ["imgA_2.jpg", "imgB_2.jpg", "imgC_2.jpg"],
    large: ["imgA_3.jpg", "imgB_3.jpg", "imgC_3.jpg"],
  };

  const largeImgEl = document.querySelector(".right-img");
  const midImgEl = document.querySelector(".container .left-img");
  const smallImgEl = document.querySelector(".img-list");
  const maskEl = document.querySelector(".mask");

  const initPage = () => {
    imgs.small.forEach((item, index) => {
      smallImgEl.innerHTML += `<li style="background-image: url(./images/${item})" 
        class="${index === 0 ? "active" : ""}">
      </li>`;
    });
  };

  const bindEvent = () => {
    smallImgEl.addEventListener("click", function (e) {
      if (e.target.tagName === "LI") {
        const lisEL = smallImgEl.querySelectorAll("li");
        for (let i = 0; i < lisEL.length; i++) {
          lisEL[i].classList.remove("active");
        }
        e.target.classList.add("active");
        const index = [].indexOf.call(lisEL, e.target);
        midImgEl.style.backgroundImage = `url(./images/${imgs["middle"][index]})`;
        largeImgEl.style.backgroundImage = `url(./images/${imgs["large"][index]})`;
      }
    });

    midImgEl.addEventListener("mousemove", function (e) {
      maskEl.style.opacity = 1;
      largeImgEl.style.opacity = 1;

      // 根据是不傲位置计算遮罩层的位置
      let left = e.clientX - midImgEl.offsetLeft - maskEl.offsetWidth / 2;
      let top = e.clientY - midImgEl.offsetTop - maskEl.offsetHeight / 2;

      if (left <= 0) {
        left = 0;
      } else if (left >= midImgEl.offsetWidth - maskEl.offsetWidth) {
        left = midImgEl.offsetWidth - maskEl.offsetWidth;
      }

      if (top <= 0) {
        top = 0;
      } else if (top >= midImgEl.offsetHeight - maskEl.offsetHeight) {
        top = midImgEl.offsetHeight - maskEl.offsetHeight;
      }

      maskEl.style.left = left + "px";
      maskEl.style.top = top + "px";
      largeImgEl.style.backgroundPositionX = -left + "px";
      largeImgEl.style.backgroundPositionY = -top + "px";
    });

    midImgEl.addEventListener("mouseleave", function () {
      maskEl.style.opacity = 0;
      largeImgEl.style.opacity = 0;
    });
  };

  const main = () => {
    initPage();
    bindEvent();
  };

  main();
})();
